//
//  RegisterViewController.m
//  iStore
//
//  Created by MacDev on 15/4/15.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//

#import "RegisterViewController.h"
#import "NewLogViewController.h"
#import "RequestEngine.h"
#import "PersonalMessageViewController.h"

//正则表达式
#define kPhoneRegex @"^1[3|4|5|8][0-9]\\d{4,8}$"
#define kPassRefex  @"[0-9]\\d{5}(?!\\d)"

//------------------------------------------
@interface RegisterViewController ()

{
    BOOL _flag;
    NSTimer *_timer;//定时器
    NSTimeInterval _seconds;//倒计时
    UIView * view;
    BOOL _once;//键盘只弹一次
}

@end

@implementation RegisterViewController
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [_sendButton setEnabled:NO];
    
    self.title = @"注册";
    self.navigationItem.leftBarButtonItem.title = @"返回";
    _myPhoneNum.keyboardType = UIKeyboardTypeNumberPad;
    _verificationTextField.keyboardType = UIKeyboardTypeNumberPad;
    referrerPhone.keyboardType = UIKeyboardTypeAlphabet;
    [_sendButton  setBackgroundImage:[UIImage imageNamed:@"Rectangle_6"] forState:UIControlStateHighlighted];
    
    [_verificationCode  setBackgroundImage:[UIImage imageNamed:@"Rectangle_6"] forState:UIControlStateHighlighted];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark --同意协议按钮--
- (IBAction)agreeProtocolClick:(UIButton *)sender
{
    
    if (_flag) {
        [sender setImage:[UIImage imageNamed:@"Check-box_1.png"] forState:UIControlStateNormal];
        _flag = !_flag;
        [_sendButton setEnabled:NO];
        [_sendButton setBackgroundColor:[UIColor lightGrayColor]];
        return;
    }
    [sender setImage:[UIImage imageNamed:@"Check-box.png"] forState:UIControlStateNormal];
    [_sendButton setEnabled:YES];
    [_sendButton setBackgroundColor:[UIColor colorWithRed:91.0/255 green:195.0/255 blue:136.0/255 alpha:1]];
    
    _flag = !_flag;
    return;
}
#pragma mark --查看协议按钮 --
- (IBAction)checkProtocolClick:(UIButton *)sender
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"serviceProtocol" ofType:@"txt"];
    view = [[UIView alloc]initWithFrame:self.view.bounds];
    view.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.3];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 80, ScreenWidth-40, 40)];
    label.text = @"“声财”软件许可及服务协议";
    [label setTextColor:[UIColor whiteColor]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setBackgroundColor:[UIColor colorWithRed:91.0/255 green:195.0/255 blue:136.0/255 alpha:1.0]];
    
    UITextView *contentView = [[UITextView alloc]initWithFrame:CGRectMake(20, 120, ScreenWidth - 40, ScreenHeight - 190)];
    contentView.editable = NO;
    contentView.selectable = NO;
    [contentView setTextColor:[UIColor blackColor]];
    [contentView setText:[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]];
    
    UIButton *agreeButton = [[UIButton alloc]initWithFrame:CGRectMake(60, ScreenHeight - 60, (ScreenWidth - 150)/2, 30)];
    agreeButton.tag = 100;
    [agreeButton setTitle:@"同意" forState:UIControlStateNormal];
    [agreeButton addTarget:self action:@selector(protocolChoose:) forControlEvents:UIControlEventTouchUpInside];
    [agreeButton setBackgroundColor:[UIColor colorWithRed:91.0/255 green:195.0/255 blue:136.0/255 alpha:1.0]];
    
    UIButton *disagreeButton = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/2 + 15, ScreenHeight-60, (ScreenWidth - 150)/2, 30)];
    disagreeButton.tag = 101;
    [disagreeButton setTitle:@"不同意" forState:UIControlStateNormal];
    [disagreeButton addTarget:self action:@selector(protocolChoose:) forControlEvents:UIControlEventTouchUpInside];
    [disagreeButton setBackgroundColor:[UIColor colorWithWhite:0 alpha:.5f]];
    
    UIView *addView = [[UIView alloc]initWithFrame:CGRectMake(20,  ScreenHeight-70, ScreenWidth - 40, 50)];
    addView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:view];
    [view addSubview:addView];
    [view addSubview:label];
    [view addSubview:contentView];
    [view addSubview:agreeButton];
    [view addSubview:disagreeButton];

}
- (void)protocolChoose:(UIButton *)btn
{
    if (btn.tag == 100) {
        [_sendButton setEnabled:YES];
        _flag = YES;
        [_agreeButton setImage:[UIImage imageNamed:@"Check-box.png"] forState:UIControlStateNormal];
        [_sendButton setBackgroundColor:[UIColor colorWithRed:91.0/255 green:195.0/255 blue:136.0/255 alpha:1]];
        [view removeFromSuperview];
        return;
    }
    else if (btn.tag == 101) {
        [_sendButton setEnabled:NO];
        _flag = NO;
        [_agreeButton setImage:[UIImage imageNamed:@"Check-box_1.png"] forState:UIControlStateNormal];
        [_sendButton setBackgroundColor:[UIColor lightGrayColor]];
        [view removeFromSuperview];
        
        return;
    }
}
#pragma mark -- 申请验证 --
- (IBAction)goMessageTextViewClick:(UIButton *)sender
{
    
    if (_myPhoneNum.text == nil || [_myPhoneNum.text isEqualToString:@""]) {
        alert(@"手机号不能为空");
        return;
    }
    //调用
    
    [_verificationCode setTitle:@"60秒" forState:UIControlStateNormal];
    _seconds = 60;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdown) userInfo:nil repeats:YES];
    
    //获取验证码
    NSString *myPhone = _myPhoneNum.text;
    [RequestEngine verificationCodeWith:@{
                                          @"phone":myPhone,
                                          @"type":@"1",
                                          @"appKey":@"IOS"
                                          } completed:^(NSString *errorcode, NSDictionary *resultDict) {
                                              if (![errorcode isEqualToString:@"0"]) {
                                                  alert(@"验证码发送失败");
                                                  [_timer invalidate];
                                                  [_verificationCode setTitle:@"申请验证" forState:UIControlStateNormal];
                                                  [_verificationCode setEnabled:YES];
                                              }
                                              
                                          }];
}
- (void) countdown{
    
    _seconds--;
    NSString *time = [NSString stringWithFormat:@"%.0f秒",_seconds];
    [_verificationCode setTitle:time forState:UIControlStateNormal];
    [_verificationCode setEnabled:NO];
    
    if (_seconds==0) {
        [_timer invalidate];
        [_verificationCode setTitle:@"申请验证" forState:UIControlStateNormal];
        [_verificationCode setEnabled:YES];
    }
    
    
}

//正则表达式的判断
- (BOOL) regexFlagWith:(NSString *)regex withParameter:(NSString *)parameter{
    
    NSPredicate *pass = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    return [pass evaluateWithObject:parameter];
    
}

//提交信息
- (IBAction)sendUserInfo:(UIButton *)sender{
   
    
    if(_flag == NO){
        
        alert(@"需要选中协议");
        [sender setEnabled:NO];
       

        return;
        
    }
    
    [_timer invalidate];
    
    //获取文本框相关信息
    NSString *myPhone = _myPhoneNum.text;//手机号
    NSString *passWord = _passWord.text;//密码
    NSString *rPassWord = _rPassWord.text;//重复密码
    NSString *verCode = _verificationTextField.text;//验证码
    NSString *referenceNO = referrerPhone.text;//推荐人手机
    if (myPhone == nil || [myPhone isEqualToString:@""] || passWord == nil || [passWord isEqualToString:@""] || rPassWord == nil || [rPassWord isEqualToString:@""] || verCode == nil || [verCode isEqualToString:@""] || _verificationTextField.text == nil || [_verificationTextField.text isEqualToString:@""]) {
        
        alert(@"内容不能为空，请填写完");
 

        
        return;
    }
    if (![passWord isEqualToString:rPassWord]) {
        alert(@"两次输入的密码不同，请重新输入");

        return;
    }
    
    if(myPhone.length != 11){
        
        alert(@"您输入的手机号不符合规范，请重新输入");

        return;
    }
    
    if(_passWord.text.length < 6 || _passWord.text.length >18){
        
        alert(@"密码为6-18位数字或字母，请重新输入");

        return;
    }
    
    if (![self regexFlagWith:kPassRefex withParameter:verCode]) {
        alert(@"验证码不正确");

        return;
    }
    
    
    [self activityStart];
    
    [RequestEngine userRegWithPhoneDic:@{
                                         @"phone":myPhone,
                                         @"password":passWord,
                                         @"validateCode":verCode,
                                         @"referenceNO":referenceNO
                                         } completed:^(NSString *errorcode,NSString * result) {
                                             
                                             [self activityStop];
                                             if([errorcode isEqualToString:@"0"]&&result.length!=0){
                                                 
                                                 [[NSUserDefaults standardUserDefaults] setObject:myPhone forKey:kUserName];
                                                 [[NSUserDefaults standardUserDefaults] synchronize];
                                                 
                                                 
                                                 [[NSUserDefaults standardUserDefaults] setObject:passWord forKey:KPassword];
                                                 [[NSUserDefaults standardUserDefaults] synchronize];
                                                 
                                                 [[NSUserDefaults standardUserDefaults] setObject:result forKey:kUserId];
                                                 [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:KplatformType];
                                                 PersonalMessageViewController *person =[[PersonalMessageViewController alloc] init];
                                                 [self.navigationController pushViewController:person animated:YES];
                                             }
                                             else{
                                                 
                                                 if ([errorcode isEqualToString:@"-1"]) {
                                                     alert(@"亲,你还没联网呢!!!");

                                                 }
                                                 else{
                                                     alert(result);

                                                     
                                                 }
                                                 
                                             }
                                             
                                         }];
}

#pragma mark --输入框上移--
- (IBAction)textFiledBegin:(id)sender {
    if (!_once) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y  -= 100;
            self.view.frame = frame;
        }];
        _once = true;
    }
    
}



// 取消键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self testFileDidFinish];
    _once = false;
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self testFileDidFinish];
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y  -= 100;
        self.view.frame = frame;
    }];
    
    
}

- (void)testFileDidFinish
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame =self.view.frame;
        frame.origin.y = 0.0;
        self.view.frame = frame;
    }];
    [self.view endEditing:YES];
    
}
@end
